package complexity;

import java.util.Iterator;

public class LinkList<T> implements Iterable<T>{
    //定义一个头节点
    private Node head;
    //记录链表的长度
    private int N;
    public LinkList(){
        this.head = new Node(null,null);
        this.N=0;
    }
    public void clear(){
        this.head=null;
        this.N=0;
    }
    public boolean isEmpty(){return this.N>0;};
    public int length(){return this.N;}
    public T get(int i){
        //通过头节点开始往后找，依次找i次，就可以找到对应的元素
        Node n = head.next;
        if (i>this.N){
            throw new RuntimeException("索引越界");
        }
        for (int index = 0; index < i; index++) {
            n=n.next;
        }
        return n.item;
    }
    public void insert(T t){
        Node n =head;
        while (n.next!=null){
            n=n.next;
        }
        Node node = new Node(t, null);
        n.next=node;
        this.N++;
    }
    public void insert(int index,T t){
        //前驱节点
        Node pre = head;
        for (int i = 0; i < index-1; i++) {
            pre=head.next;
        }
        //后继节点
//        Node last = pre.next.next;
        //当前节点
        Node current = pre.next;
        Node newNode = new Node(t,current);
        pre.next  = newNode;
        this.N++;
    }
    public T remove(int i){
        Node pre =head;
        for (int index = 0; index < i; index++) {
            pre=head.next;
        }
        Node current = pre.next;
        Node next = pre.next.next;
        pre.next=next;
        this.N--;
        return current.item;
    }
    public int indexOf(T t){
        Node n = head;
        for (int i = 0;  n.next!=null; i++) {
            n=n.next;
            if (n.item.equals(t)){
                return i;
            }
        }
        return -1;
    }
    //节点类
    private class Node{
        //存储数据
        T item;
        //下一个节点
        Node next;
        public Node(T t,Node next){
            this.item=t;
            this.next=next;
        }
    }
    @Override
    public Iterator<T> iterator() {
        return new LIterator();
    }
    private class LIterator implements Iterator{
        private Node n ;
        public LIterator(){
            this.n=head;
        }
        @Override
        public boolean hasNext() {
            return n.next!=null;
        }

        @Override
        public Object next() {
            n=n.next;
            return n.item;
        }
    }
}
